package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.core.domain.entity.SysFeed;
import com.ruoyi.system.domain.SysUserFeed;
import com.ruoyi.system.service.ISysAerationService;
import com.ruoyi.system.service.ISysFeedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 投喂机信息
 *
 * @author xiongdong
 */
@RestController
@RequestMapping("/system/feed")
public class SysFeedController extends BaseController
{

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysAerationService aerationService;
    
    @Autowired
    private ISysFeedService feedService;

    @PreAuthorize("@ss.hasPermi('system:feed:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysFeed sysFeed)
    {
        startPage();
        List<SysFeed> list = feedService.selectSysFeedList(sysFeed);
        return getDataTable(list);
    }

    @Log(title = "投喂机管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:feed:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysFeed sysFeed)
    {
        List<SysFeed> list = feedService.selectSysFeedList(sysFeed);
        ExcelUtil<SysFeed> util = new ExcelUtil<SysFeed>(SysFeed.class);
        util.exportExcel(response, list, "投喂机数据");
    }

    /**
     * 根据投喂机编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:feed:query')")
    @GetMapping(value = "/{feedId}")
    public AjaxResult getInfo(@PathVariable Long feedId)
    {
        feedService.checkFeedDataScope(feedId);
        return success(feedService.selectFeedById(feedId));
    }

    /**
     * 新增投喂机
     */
    @PreAuthorize("@ss.hasPermi('system:feed:add')")
    @Log(title = "投喂机管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysFeed sysFeed)
    {
        if (UserConstants.NOT_UNIQUE.equals(feedService.checkFeedNameUnique(sysFeed)))
        {
            return error("新增投喂机'" + sysFeed.getFeedName() + "'失败，投喂机名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(feedService.checkFeedKeyUnique(sysFeed)))
        {
            return error("新增投喂机'" + sysFeed.getFeedName() + "'失败，投喂机权限已存在");
        }
        sysFeed.setCreateBy(getUsername());
        return toAjax(feedService.insertFeed(sysFeed));

    }

    /**
     * 修改保存投喂机
     */
    @PreAuthorize("@ss.hasPermi('system:feed:edit')")
    @Log(title = "投喂机管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysFeed sysFeed)
    {
        feedService.checkFeedAllowed(sysFeed);
        feedService.checkFeedDataScope(sysFeed.getFeedId());
        if (UserConstants.NOT_UNIQUE.equals(feedService.checkFeedNameUnique(sysFeed)))
        {
            return error("修改投喂机'" + sysFeed.getFeedName() + "'失败，投喂机名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(feedService.checkFeedKeyUnique(sysFeed)))
        {
            return error("修改投喂机'" + sysFeed.getFeedName() + "'失败，投喂机权限已存在");
        }
        sysFeed.setUpdateBy(getUsername());

        if (feedService.updateFeed(sysFeed) > 0)
        {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
            {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }
        return error("修改投喂机'" + sysFeed.getFeedName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:feed:edit')")
    @Log(title = "投喂机管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysFeed sysFeed)
    {
        feedService.checkFeedAllowed(sysFeed);
        feedService.checkFeedDataScope(sysFeed.getFeedId());
        return toAjax(feedService.authDataScope(sysFeed));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:feed:edit')")
    @Log(title = "投喂机管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysFeed sysFeed)
    {
        feedService.checkFeedAllowed(sysFeed);
        feedService.checkFeedDataScope(sysFeed.getFeedId());
        sysFeed.setUpdateBy(getUsername());
        return toAjax(feedService.updateFeedStatus(sysFeed));
    }

    /**
     * 删除投喂机
     */
    @PreAuthorize("@ss.hasPermi('system:feed:remove')")
    @Log(title = "投喂机管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{feedIds}")
    public AjaxResult remove(@PathVariable Long[] feedIds)
    {
        return toAjax(feedService.deleteFeedByIds(feedIds));
    }

    /**
     * 获取投喂机选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:feed:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        return success(feedService.selectFeedAll());
    }

    /**
     * 查询已分配用户投喂机列表
     */
    @PreAuthorize("@ss.hasPermi('system:feed:list')")
    @GetMapping("/authUser/allocatedList")
    public TableDataInfo allocatedList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectAllocatedList3(user);
        return getDataTable(list);
    }

    /**
     * 查询未分配用户投喂机列表
     */
    @PreAuthorize("@ss.hasPermi('system:feed:list')")
    @GetMapping("/authUser/unallocatedList")
    public TableDataInfo unallocatedList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUnallocatedList3(user);
        return getDataTable(list);
    }

    /**
     * 取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:feed:edit')")
    @Log(title = "投喂机管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody SysUserFeed userFeed)
    {
        return toAjax(feedService.deleteUserFeed(userFeed));
    }

    /**
     * 批量取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:feed:edit')")
    @Log(title = "投喂机管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long feedId, Long[] userIds)
    {
        return toAjax(feedService.deleteDeptFeeds(feedId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@ss.hasPermi('system:feed:edit')")
    @Log(title = "投喂机管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long feedId, Long[] userIds)
    {
        feedService.checkFeedDataScope(feedId);
        return toAjax(feedService.insertDeptFeeds(feedId, userIds));
    }

    /**
     * 获取对应投喂机渔场树列表
     */
    @PreAuthorize("@ss.hasPermi('system:feed:query')")
    @GetMapping(value = "/deptTree/{feedId}")
    public AjaxResult deptTree(@PathVariable("feedId") Long feedId)
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByFeedId(feedId));
        ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
        return ajax;
    }
}
